const UserService = require("../../services/admin/UserService");
const JWT = require("../../util/JWT");
const UserController = {
  login: async (req, res) => {
    // console.log(req.body);
    // req.body
    let result = await UserService.login(req.body);

    if (result.length === 0) {
      res.send({
        code: "-1",
        error: "用户名密码不匹配",
      });
    } else {
      // 用户名密码正确,生成token
      const token = JWT.generate(
        {
          _id: result[0]._id,
          username: result[0].username,
        },
        ".5h"
      );
      res.header("Authorization", token);
      res.send({
        ActiveType: "OK",
        data: {
          username: result[0].username,
          gender: result[0].gender ? result[0].gender : 0,
          introduction: result[0].introduction,
          avatar: result[0].avatar,
          role: result[0].role,
        },
      });
    }
  },
  uploadFile: async (req, res) => {
    const { username, introduction, gender } = req.body;
    const token = req.headers["authorization"].split(" ")[1];
    const avatar = req.file ? `/avataruploads/${req.file.filename}` : "";
    var payload = JWT.verify(token);
    // 调用 service 模块更新数据
    await UserService.uploadFile({
      _id: payload._id,
      username,
      introduction,
      gender: Number(gender),
      avatar,
    });

    res.send({
      ActionType: "OK",
      data: {
        username,
        introduction,
        gender: Number(gender),
        avatar,
      },
    });
  },
  addUser: async (req, res) => {
    const { username, introduction, gender, role, password } = req.body;
    const avatar = req.file ? `/avataruploads/${req.file.filename}` : "";
    // 调用 service 模块更新数据
    await UserService.addUser({
      username,
      introduction,
      gender: Number(gender),
      avatar,
      role,
      password,
    });

    res.send({
      ActionType: "OK",
    });
  },
  getUserList: async (req, res) => {
    const result = await UserService.getUserList();

    res.send({
      ActionType: "OK",
      data: result,
    });
  },
  deleteUser: async (req, res) => {
    await UserService.deleteUser({ _id: req.params.id });
    res.send({
      ActionType: "OK",
    });
  }
};

module.exports = UserController;
